package com.papper.mng.dialect.tag;

import com.papper.common.config.PapperStorage;
import com.papper.common.enums.utils.EnumsUtil;
import com.papper.mng.dialect.PapperDialect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

/**
 * @author:LaJiao
 * @date 2022年04月02日
 * @time 08时06
 * @Description:
 */
public class PaEnumStyleTag extends AbstractElementTagProcessor {
    private static final Logger logger   = LoggerFactory.getLogger(PaEnumStyleTag.class);
    // 标签名
    private static final String TAG_NAME = "enumStyle";

    public PaEnumStyleTag(String dialectPrefix) {
        super(TemplateMode.HTML, dialectPrefix, TAG_NAME, true, null, false, PapperDialect.PRECEDENCE);
    }

    @Override
    protected void doProcess(ITemplateContext iTemplateContext, IProcessableElementTag iProcessableElementTag, IElementTagStructureHandler iElementTagStructureHandler) {
        //  获取前端页面传递的属性
        String enumName = iProcessableElementTag.getAttributeValue("enum");
        String code     = iProcessableElementTag.getAttributeValue("code");
        // Enum获取
        StringBuilder enumPath = new StringBuilder();
        enumPath.append(PapperStorage.Config("SystemConfig", "base.enum.package", "com.papper.common.enums."));
        enumPath.append(enumName);
        enumPath.append("Enum");
        Class  enumClass = null;
        String value     = code;
        try {
            enumClass = Class.forName(enumPath.toString());
            value = EnumsUtil.enumValue(enumClass, value);
        } catch (ClassNotFoundException e) {
            logger.error("属性对象不存在:[{}],[{}]", enumName, enumPath);
        }
        // 创建标签
        IModelFactory modelFactory = iTemplateContext.getModelFactory();
        IModel        model        = modelFactory.createModel();
        model.add(modelFactory.createOpenElementTag(String.format("selction class='%s-%s'", enumName, code)));
        model.add(modelFactory.createText(value));
        model.add(modelFactory.createCloseElementTag("selction"));
        iElementTagStructureHandler.replaceWith(model, false);
    }
}
